package com.group1.realtime.app.dwd.log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.group1.realtime.app.BaseAppV1;
import com.group1.realtime.common.Constant;
import com.group1.realtime.util.AtguiguUtil;
import com.group1.realtime.util.FlinkSinkUtil;
import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

import java.util.HashMap;


public class BaseLogApp extends BaseAppV1 {

    private final String START = "start";
    private final String DISPLAY = "display";
    private final String ERR = "err";
    private final String PAGE = "page";
    private final String ACTION = "action";
    private final String APPVIDEO = "appVideo";


    public static void main(String[] args) {
        new BaseLogApp().init(
                2011,
                2,
                "BaseLogApp",
                Constant.TOPIC_ODS_LOG
        );
    }

    @Override
    protected void handle(StreamExecutionEnvironment env, DataStreamSource<String> stream) {

        SingleOutputStreamOperator<JSONObject> etlStream = etl(stream);

        SingleOutputStreamOperator<JSONObject> validatedStream = validateNewOrOld(etlStream);

        HashMap<String, DataStream<String>> sixStreams = splitStream(validatedStream);

        writeToKafka(sixStreams);
    }

    private void writeToKafka(HashMap<String, DataStream<String>> sixStreams) {
        sixStreams.get(START).addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_TRAFFIC_START));
        sixStreams.get(DISPLAY).addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_TRAFFIC_DISPLAY));
        sixStreams.get(ACTION).addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_TRAFFIC_ACTION));
        sixStreams.get(ERR).addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_TRAFFIC_ERR));
        sixStreams.get(PAGE).addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_TRAFFIC_PAGE));
        sixStreams.get(APPVIDEO).addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_TRAFFIC_APPVIDEO));
    }

    private HashMap<String, DataStream<String>> splitStream(SingleOutputStreamOperator<JSONObject> validatedStream) {

        OutputTag<String> displayTag = new OutputTag<String>("display") {
        };
        OutputTag<String> actionTag = new OutputTag<String>("action") {
        };
        OutputTag<String> errTag = new OutputTag<String>("err") {
        };
        OutputTag<String> pageTag = new OutputTag<String>("page") {
        };
        OutputTag<String> appVideoTag = new OutputTag<String>("appVideo") {
        };

        SingleOutputStreamOperator<String> start = validatedStream.process(new ProcessFunction<JSONObject, String>() {
            @Override
            public void processElement(JSONObject obj,
                                       Context context,
                                       Collector<String> out) throws Exception {
                JSONObject start = obj.getJSONObject("start");
                if (start != null) {
                    out.collect(obj.toJSONString());
                } else {
                    JSONObject common = obj.getJSONObject("common");
                    JSONObject page = obj.getJSONObject("page");
                    Long ts = obj.getLong("ts");

                    JSONArray displays = obj.getJSONArray("displays");
                    JSONObject displayInfo = new JSONObject();
                    if (displays != null) {
                        for (int i = 0; i < displays.size(); i++) {
                            JSONObject display = displays.getJSONObject(i);
                            displayInfo.put("common", common);
                            displayInfo.put("display", display);
                            displayInfo.put("page", page);
                            displayInfo.put("ts", ts);
                            context.output(displayTag, displayInfo.toJSONString());
                        }
                        obj.remove("displays");
                    }

                    JSONArray actions = obj.getJSONArray("actions");
                    if (actions != null) {
                        for (int i = 0; i < actions.size(); i++) {
                            JSONObject actionInfo = new JSONObject();
                            JSONObject action = actions.getJSONObject(i);
                            actionInfo.put("common", common);
                            actionInfo.put("action",action);
                            actionInfo.put("page",page);
                            actionInfo.put("ts",ts);
                            context.output(actionTag, actionInfo.toJSONString());
                        }
                        obj.remove("actions");
                    }

                    JSONObject err = obj.getJSONObject("err");
                    if (err != null) {
                        context.output(errTag, obj.toString());
                        obj.remove("err");
                    }

                    JSONObject pageInfo = new JSONObject();
                    if (page != null) {
                        pageInfo.put("common", common);
                        pageInfo.put("page", page);
                        pageInfo.put("ts", ts);
                        context.output(pageTag, pageInfo.toJSONString());
                    }
                    obj.remove("page");
                }

                if (obj.getJSONObject("appVideo") != null) {
                    context.output(appVideoTag, obj.toJSONString());
                }
            }
        });

        HashMap<String, DataStream<String>> map = new HashMap<>();

        map.put(START, start);
        map.put(DISPLAY, start.getSideOutput(displayTag));
        map.put(ACTION, start.getSideOutput(actionTag));
        map.put(ERR, start.getSideOutput(errTag));
        map.put(PAGE, start.getSideOutput(pageTag));
        map.put(APPVIDEO, start.getSideOutput(appVideoTag));

        return map;
    }

    private SingleOutputStreamOperator<JSONObject> validateNewOrOld(SingleOutputStreamOperator<JSONObject> etlStream) {
        return etlStream
                .keyBy(json -> json.getJSONObject("common").getString("uid"))
                .map(new RichMapFunction<JSONObject, JSONObject>() {

                    private ValueState<String> firstVisitDateState;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        firstVisitDateState = getRuntimeContext().getState(new ValueStateDescriptor<String>("isNewState", String.class));
                    }

                    @Override
                    public JSONObject map(JSONObject jsonObject) throws Exception {
                        JSONObject common = jsonObject.getJSONObject("common");
                        String isNew = common.getString("is_new");
                        Long ts = jsonObject.getLong("ts");

                        String today = AtguiguUtil.toDate(ts);

                        if ("1".equals(isNew)) {
                            if (firstVisitDateState.value() == null) {
                                firstVisitDateState.update(today);
                            } else if(!today.equals(firstVisitDateState.value())){
                                common.put("is_new", 0);
                            }
                        } else if (firstVisitDateState.value() == null) {
                            String yesterday = AtguiguUtil.toYesterday(ts);
                            firstVisitDateState.update(yesterday);
                        }
                        return jsonObject;
                    }
                });
    }

    private SingleOutputStreamOperator<JSONObject> etl(DataStreamSource<String> stream) {
        return stream
                .filter(new FilterFunction<String>() {
                    @Override
                    public boolean filter(String value) throws Exception {
                        try {
                            JSON.parseObject(value);
                        } catch (Exception e) {
                            System.out.println("elt:我要JSON文件，你瞅瞅你传了啥");
                            return false;
                        }
                        return true;
                    }
                })
                .map(JSON::parseObject);

    }
}
